<template>
  <div class="notebook-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-content">
        <h1 class="title">
          <el-icon><Notebook /></el-icon>
          中医记事本
        </h1>
        <div class="header-actions">
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新建笔记
          </el-button>
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- 侧边栏分类 -->
      <div class="sidebar">
        <div class="category-list">
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ active: currentCategory === category.id }"
            @click="setCurrentCategory(category.id)"
          >
            <div class="category-color" :style="{ backgroundColor: category.color }"></div>
            <span class="category-name">{{ category.name }}</span>
            <span class="category-count" v-if="category.id !== 'all'">
              {{ getCategoryCount(category.id) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 笔记列表 -->
      <div class="notes-content">
        <!-- 搜索栏 -->
        <div class="search-section">
          <div class="search-bar">
            <el-input
              v-model="searchQuery"
              placeholder="搜索笔记标题或内容..."
              clearable
              @input="handleSearch"
              @clear="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="search-options">
            <el-checkbox v-model="searchInContent" @change="handleSearch">
              搜索内容
            </el-checkbox>
            <el-checkbox v-model="searchInTitle" @change="handleSearch">
              搜索标题
            </el-checkbox>
            <el-select v-model="searchType" placeholder="搜索类型" @change="handleSearch" style="width: 120px;">
              <el-option label="全部" value="all" />
              <el-option label="文字" value="text" />
              <el-option label="图片" value="image" />
              <el-option label="语音" value="audio" />
            </el-select>
          </div>
          
          <div v-if="searchQuery" class="search-results-info">
            <span>找到 {{ searchResults.length }} 条相关笔记</span>
            <el-button type="text" @click="clearSearch">
              <el-icon><Close /></el-icon>
              清除搜索
            </el-button>
          </div>
        </div>

        <div class="notes-header">
          <h2>{{ getCurrentCategoryName() }}</h2>
          <span class="notes-count">{{ displayNotes.length }} 条笔记</span>
        </div>

        <div class="notes-grid">
          <div
            v-for="note in displayNotes"
            :key="note.id"
            class="note-card"
            @click="editNote(note)"
          >
            <div class="note-header">
              <h3 class="note-title">
                <span v-if="searchQuery && isHighlighted(note.title)" v-html="highlightText(note.title)"></span>
                <span v-else>{{ note.title }}</span>
              </h3>
              <div class="note-actions">
                <el-button
                  type="danger"
                  size="small"
                  circle
                  @click.stop="deleteNote(note.id)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            
            <div class="note-content">
              <div v-if="note.type === 'text'" class="text-content">
                <span v-if="searchQuery && isHighlighted(note.content)" v-html="highlightText(note.content.substring(0, 100))"></span>
                <span v-else>{{ note.content.substring(0, 100) }}{{ note.content.length > 100 ? '...' : '' }}</span>
              </div>
              <div v-else-if="note.type === 'image'" class="image-content">
                <img :src="note.mediaUrl" alt="图片笔记" />
              </div>
              <div v-else-if="note.type === 'audio'" class="audio-content">
                <audio controls>
                  <source :src="note.mediaUrl" type="audio/mpeg">
                </audio>
              </div>
            </div>

            <div class="note-footer">
              <span class="note-category">
                {{ getCategoryName(note.category) }}
              </span>
              <span class="note-time">
                {{ formatTime(note.updatedAt) }}
              </span>
            </div>
          </div>
        </div>

        <div v-if="displayNotes.length === 0" class="empty-state">
          <el-icon size="64"><Document /></el-icon>
          <p v-if="searchQuery">没有找到相关笔记</p>
          <p v-else>暂无笔记，点击"新建笔记"开始记录</p>
        </div>
      </div>
    </div>

    <!-- 添加/编辑笔记对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingNote ? '编辑笔记' : '新建笔记'"
      width="60%"
      @close="resetForm"
    >
      <el-form :model="noteForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="noteForm.title" placeholder="请输入笔记标题" />
        </el-form-item>
        
        <el-form-item label="分类">
          <el-select v-model="noteForm.category" placeholder="选择分类">
            <el-option
              v-for="category in categories.filter(c => c.id !== 'all')"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="类型">
          <el-radio-group v-model="noteForm.type">
            <el-radio label="text">文字</el-radio>
            <el-radio label="image">图片</el-radio>
            <el-radio label="audio">语音</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容" v-if="noteForm.type === 'text'">
          <el-input
            v-model="noteForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入笔记内容"
          />
        </el-form-item>

        <el-form-item label="上传" v-if="noteForm.type === 'image'">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleImageChange"
            accept="image/*"
          >
            <el-button type="primary">选择图片</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="录音" v-if="noteForm.type === 'audio'">
          <div class="audio-recorder">
            <el-button
              :type="isRecording ? 'danger' : 'primary'"
              @click="toggleRecording"
            >
              <el-icon v-if="!isRecording"><Microphone /></el-icon>
              <el-icon v-else><VideoPause /></el-icon>
              {{ isRecording ? '停止录音' : '开始录音' }}
            </el-button>
            <audio v-if="audioUrl" controls class="recorded-audio">
              <source :src="audioUrl" type="audio/wav">
            </audio>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveNote">
            {{ editingNote ? '更新' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useNotebookStore } from '../stores/notebook'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useNotebookStore()

// 响应式数据
const showAddDialog = ref(false)
const editingNote = ref(null)
const isRecording = ref(false)
const audioUrl = ref('')
const mediaRecorder = ref(null)
const audioChunks = ref([])

// 搜索相关数据
const searchQuery = ref('')
const searchInContent = ref(true)
const searchInTitle = ref(true)
const searchType = ref('all')

// 表单数据
const noteForm = reactive({
  title: '',
  content: '',
  category: 'personal',
  type: 'text',
  mediaUrl: ''
})

// 计算属性
const categories = computed(() => store.categories)
const currentCategory = computed(() => store.currentCategory)
const filteredNotes = computed(() => store.filteredNotes)

// 搜索逻辑
const searchResults = computed(() => {
  if (!searchQuery.value.trim()) {
    return filteredNotes.value
  }

  const query = searchQuery.value.toLowerCase()
  const results = []

  filteredNotes.value.forEach(note => {
    let match = false

    // 检查笔记类型
    if (searchType.value !== 'all' && note.type !== searchType.value) {
      return
    }

    // 搜索标题
    if (searchInTitle.value && note.title && note.title.toLowerCase().includes(query)) {
      match = true
    }

    // 搜索内容
    if (searchInContent.value && note.content && note.content.toLowerCase().includes(query)) {
      match = true
    }

    if (match) {
      results.push(note)
    }
  })

  return results
})

// 显示的笔记列表
const displayNotes = computed(() => {
  return searchQuery.value ? searchResults.value : filteredNotes.value
})

// 方法
const setCurrentCategory = (category) => {
  store.setCurrentCategory(category)
}

const getCategoryCount = (categoryId) => {
  return store.notes.filter(note => note.category === categoryId).length
}

const getCurrentCategoryName = () => {
  const category = categories.value.find(c => c.id === currentCategory.value)
  return category ? category.name : '全部'
}

const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未知'
}

const formatTime = (timeString) => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

const editNote = (note) => {
  editingNote.value = note
  noteForm.title = note.title
  noteForm.content = note.content
  noteForm.category = note.category
  noteForm.type = note.type
  noteForm.mediaUrl = note.mediaUrl
  audioUrl.value = note.mediaUrl
  showAddDialog.value = true
}

const deleteNote = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条笔记吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    store.deleteNote(id)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleImageChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    noteForm.mediaUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const toggleRecording = () => {
  if (!isRecording.value) {
    startRecording()
  } else {
    stopRecording()
  }
}

const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    mediaRecorder.value = new MediaRecorder(stream)
    audioChunks.value = []

    mediaRecorder.value.ondataavailable = (event) => {
      audioChunks.value.push(event.data)
    }

    mediaRecorder.value.onstop = () => {
      const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' })
      audioUrl.value = URL.createObjectURL(audioBlob)
      noteForm.mediaUrl = audioUrl.value
    }

    mediaRecorder.value.start()
    isRecording.value = true
  } catch (error) {
    ElMessage.error('无法访问麦克风')
  }
}

const stopRecording = () => {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop()
    mediaRecorder.value.stream.getTracks().forEach(track => track.stop())
    isRecording.value = false
  }
}

const saveNote = () => {
  if (!noteForm.title.trim()) {
    ElMessage.warning('请输入笔记标题')
    return
  }

  if (editingNote.value) {
    store.updateNote(editingNote.value.id, noteForm)
    ElMessage.success('更新成功')
  } else {
    store.addNote(noteForm)
    ElMessage.success('添加成功')
  }

  showAddDialog.value = false
  resetForm()
}

const resetForm = () => {
  editingNote.value = null
  noteForm.title = ''
  noteForm.content = ''
  noteForm.category = 'personal'
  noteForm.type = 'text'
  noteForm.mediaUrl = ''
  audioUrl.value = ''
  isRecording.value = false
}

// 搜索相关方法
const handleSearch = () => {
  console.log('搜索查询:', searchQuery.value)
  console.log('搜索内容:', searchInContent.value)
  console.log('搜索标题:', searchInTitle.value)
  console.log('搜索类型:', searchType.value)
  console.log('搜索结果数量:', searchResults.value.length)
}

const clearSearch = () => {
  searchQuery.value = ''
  searchInContent.value = true
  searchInTitle.value = true
  searchType.value = 'all'
  console.log('搜索已清除')
}

const isHighlighted = (text) => {
  if (!searchQuery.value || !text) return false
  return text.toLowerCase().includes(searchQuery.value.toLowerCase())
}

const highlightText = (text) => {
  if (!searchQuery.value || !text) return text
  
  try {
    const regex = new RegExp(`(${searchQuery.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi')
    return text.replace(regex, '<mark style="background-color: #ffd04b; padding: 2px 4px; border-radius: 2px;">$1</mark>')
  } catch (error) {
    console.error('高亮文本时出错:', error)
    return text
  }
}
</script>

<style scoped>
.notebook-container {
  min-height: 100vh;
  background: #f5f7fa;
}

.header {
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 1rem 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #303133;
  font-size: 1.5rem;
}

.main-content {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 2rem;
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 2rem;
}

.sidebar {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-item:hover {
  background: #f5f7fa;
}

.category-item.active {
  background: #ecf5ff;
  color: #409eff;
}

.category-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.category-name {
  flex: 1;
  font-weight: 500;
}

.category-count {
  background: #f0f0f0;
  color: #666;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
}

.notes-content {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #ebeef5;
}

.search-bar {
  margin-bottom: 1rem;
}

.search-options {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 0.5rem;
  flex-wrap: wrap;
}

.search-results-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 0.875rem;
}

.notes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #ebeef5;
}

.notes-header h2 {
  color: #303133;
  font-size: 1.25rem;
}

.notes-count {
  color: #909399;
  font-size: 0.875rem;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
}

.note-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.note-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.75rem;
}

.note-title {
  font-size: 1rem;
  color: #303133;
  margin: 0;
  flex: 1;
  margin-right: 0.5rem;
}

.note-content {
  margin-bottom: 1rem;
}

.text-content {
  color: #606266;
  line-height: 1.5;
  font-size: 0.875rem;
}

.image-content img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.audio-content audio {
  width: 100%;
}

.note-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.75rem;
  color: #909399;
}

.note-category {
  background: #f0f0f0;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
}

.empty-state {
  text-align: center;
  padding: 3rem;
  color: #909399;
}

.empty-state p {
  margin-top: 1rem;
  font-size: 1rem;
}

.audio-recorder {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.recorded-audio {
  width: 100%;
}

.upload-demo {
  width: 100%;
}

@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .header-content {
    padding: 0 1rem;
  }
  
  .main-content {
    padding: 0 1rem;
  }
  
  .notes-grid {
    grid-template-columns: 1fr;
  }
  
  .search-options {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}
</style> 